package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserSeriviceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public User login(UserLoginDTO dto) {
        /*
            TODO 1、通过HttpClient，构造登录凭证校验请求
                 1.1、构造请求参数
                 1.2、调用HttpClientUtil工具类进行想微信发起请求进行验证
        */
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        String res = HttpClientUtil.doGet(url, paramMap);


        /* TODO 2、解析响应结果，获取openid */
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = (String) jsonObject.get("openid");
        log.info("openid:{}", openid);
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.USER_NOT_LOGIN);
        }
        /* TODO 3、判断是否为新用户，根据openid查询user表 */
        User user = userMapper.selectOpenId(openid);

        /* TODO 4、如果是新用户则注册到 user表中，如果不是则返回 user对象*/
        if (user == null) {
            user = new User();
            user.setCreateTime(LocalDateTime.now());
            user.setOpenid(openid);
            user.setName(openid.substring(0, 10));
            userMapper.insert(user);
        }
        log.info("user:{}", user);
        return user;
    }
}
